package pers.richard.ormybatis.bean.mapping;

import java.util.stream.Stream;

import pers.richard.ormybatis.bean.field.FieldName;
import pers.richard.ormybatis.bean.sql.OperationExpressionBean;
import pers.richard.ormybatis.bean.sql.OrderByBean;
import pers.richard.ormybatis.bean.sql.Where;
import pers.richard.ormybatis.util.CaseFormatUtil;

/**
 * 查询select Field参数bean
 */
public class SelectFieldMappingBean extends BaseMappingBean{
	
	/**
	 * 表的字段名
	 */
	private String field;
	
	/**
	 * where查询条件
	 */
	private Where where;
	
	public SelectFieldMappingBean(){}
	
	public SelectFieldMappingBean(String tableName, String primaryKeyName, String field, Where where, Class poClz, boolean lowerUnderscore){
		super(tableName, primaryKeyName);
		this.field = field;
		this.where = where;
		//默认按is_deleted = 0
		if (Stream.of(poClz.getDeclaredFields()).anyMatch(p -> p.getName().equals("isDeleted"))) {
			if (where.getOperExpressList().stream().noneMatch(p -> p.getField().equalsIgnoreCase("is_deleted") )) {
				where.eq(new FieldName("is_deleted"), 0);
			}
		}
		for (OperationExpressionBean operationExpressionBean : this.where.getOperExpressList()) {
			String operationExpressionField = operationExpressionBean.getField();
			operationExpressionField = lowerUnderscore ? CaseFormatUtil.toLowerUnderscore(operationExpressionField) : CaseFormatUtil.toLowerCamel(operationExpressionField);
			operationExpressionBean.setField(operationExpressionField);
		}
		for (OrderByBean orderByBean : this.where.getOrderByList()) {
			String orderByBeanField = orderByBean.getField();
			orderByBeanField = lowerUnderscore ? CaseFormatUtil.toLowerUnderscore(orderByBeanField) : CaseFormatUtil.toLowerCamel(orderByBeanField);
			orderByBean.setField(orderByBeanField);
		}
	}
	
	public String getField() {return field;}
	public void setField(String field) {this.field = field;}
	
	public Where getWhere() {return where;}
	public void setWhere(Where where) {this.where = where;}
}
